#!/bin/bash
if [ -z "$1" ]; then
    echo "Usage: $0 --component component-name/image-location [--component-parameters-name component-parameters-value ...]"
    echo "Example: claimed --component blumenstiel/claimed-generate-random-numbers --num_random 5"
    echo "or (deprecated)"
    echo "Usage: $0 component-name/image-location [component-parameters-name=component-parameters-value ...]"
    echo "Example: claimed blumenstiel/claimed-generate-random-numbers num_random=5"
    exit 1
fi

# Create operator and gridwrapper with C3
if [ $1 = "create" ]; then
  if ! command -v c3_create_operator &> /dev/null; then
      echo "CLAIMED C3 not found. Install with 'pip install claimed-c3'"
      exit 1
  fi
  if [ $2 = "operator" ]; then
    c3_create_operator ${@:3}
  elif [ $2 = "gridwrapper" ]; then
    c3_create_gridwrapper ${@:3}
  else
    echo "C3 can only create 'operator' and 'gridwrapper'."
    exit 1
  fi
  exit 0
fi

# Nothing above matched, so we assume we want to run a component

envs=""
if [[ $1 == "--component" ]]; then
  image=$2
  shift 2
  for var in "$@"; do
    if [[ $var == "--"* ]]; then
      envs="${envs} --env ${var:2}="
    else
      envs="${envs}${var}"
    fi
  done
else
  echo "Assuming arguments contain = sign, you need to provide the --component to run, aborting"
  exit 1
fi



if [[ "$image" != */* ]]; then
  image=docker.io/claimed/$image
fi

if [[ "$image" != *:* ]]; then
  image=$image:latest
fi

if [[ "$image" != *containerless* ]]; then
  if [ -z ${CLAIMED_DATA_PATH+x} ]; then
    echo "CLAIMED_DATA_PATH variable not set, not mounting /data to the CLAIMED component"
    docker run $envs $image
  else
    echo "CLAIMED_DATA_PATH variable is set, mounting $CLAIMED_DATA_PATH to /opt/app-root/src/data"
    docker run $envs -u 0 -v `echo $CLAIMED_DATA_PATH`:/opt/app-root/src/data:z $image
  fi
else
  echo "Entering containerless operation"
  if [ -z ${CLAIMED_CONTAINERLESS_OPERATOR_PATH+x} ]; then
    echo "CLAIMED_CONTAINERLESS_OPERATOR_PATH not set, aborting"
    exit 1
  else
    containerlesscomponentpath=`sed "s/containerless//g" <<< "$image"`
    containerlesscomponentpath=`sed "s/:/./g" <<< "$containerlesscomponentpath"`
    containerlesscomponent=$containerlesscomponentpath"/runnable.py"
    command="python "$CLAIMED_CONTAINERLESS_OPERATOR_PATH"/"$containerlesscomponent" "$envs                                                                                               
    echo "Executing: "$command
    source $CLAIMED_CONTAINERLESS_OPERATOR_PATH'/'$containerlesscomponentpath"/claimedenv/bin/activate"
    chmod 755 $CLAIMED_CONTAINERLESS_OPERATOR_PATH"/"$containerlesscomponent
    $command
  fi
fi
